//
//  LBMUserAccountViewModel.swift
//  微博
//
//  Created by 刘保满 on 16/5/22.
//  Copyright © 2016年 itheima. All rights reserved.
//
//用户视图模型

/*
 1. 封装网络请求
 2. 存储用户数据
 3. 对外提供本地缓存的用户数据
 */

import UIKit

private let userInfoKey = "com.itheima.userInfoKey"

class LBMUserAccountViewModel: NSObject {
    
    //单例对象
    static let sharedAccountViewModel: LBMUserAccountViewModel = LBMUserAccountViewModel()
    
    //模型属性
    var userAccount: LBMUserAccount?
    
    //重写构造方法
    private override init() {
        super.init()
        
        //读取数据
        userAccount = loadUserAccount()
        
    }
    
    //是否登录
    var userLogin: Bool {
        
        if userAccount?.expires_date?.compare(NSDate()) == .OrderedDescending {
            
            return true
            
        }
        
        //如果过期,需要将userAccount设置为nil
        userAccount = nil
        
        return false
        
        
    }
    
    
    //增加一个属性 头像的URL
    var headURL: NSURL? {
        
        get {
            
            return NSURL(string: userAccount?.avatar_large ?? "")
            
        }
        
    }
    
    
    
}

//封装网络请求
extension LBMUserAccountViewModel {
    
    //使用之前获得的code 获取用户授权的令牌 token   获取授权
    func loadAccessToken(code: String, finished: (isSuccess: Bool) -> ()) {
        
        LBMNetworkTools.sharedTools.loadAccessToken(code) { (responsseObject, error) in
            
            
            if error != nil {
                finished(isSuccess: false)
                //请求失败直接return
                return
                
            }
            //请求成功
             print(responsseObject)
            //加载用户信息 //在闭包内用self.
            self.loaduserInfo(responsseObject, finished: finished)
            
           
        }
        
        
        
    }
    
    //继续请求用户信息
    private func loaduserInfo(response: AnyObject?, finished: (isSuccess: Bool) -> ()) {
        
        guard let result = response as? [String: AnyObject] else {
            
            finished(isSuccess: false)
            //没有,直接返回
            return
        }
        
        LBMNetworkTools.sharedTools.loaduserInfo(result) { (responsseObject, error) in
            
            if error != nil {
                
                finished(isSuccess: false)
                //失败直接返回
                return
            }
            //请求成功
            guard var dict = responsseObject as? [String : AnyObject] else {
                //没有数据直接返回
                finished(isSuccess: false)
                return
            }
            
            //想把第二次请求获得的token,uid 和这次请求的数据合并在一起,保存到本地,以供下次使用
            for (key, value) in result {
                //把第二次请求的数据添加到这次请求的用户信息的字典中
                dict[key] = value
            }
            
            //把上面合并后的字典保存
            self.saveUserAccount(dict)
            
            //成功回调
            finished(isSuccess: true)
        }

    }
}

//保存数据
extension LBMUserAccountViewModel {
    
    //存储数据
    func saveUserAccount(dict: [String: AnyObject]) {
        
        //先转换为模型对象 是为了去除不想要的键值
        let user = LBMUserAccount(dict: dict)
        
        //在这里赋值,是为了解决 有未登录状态,点击登录,进入授权界面,登录成功进入欢迎界面,userAccount值为ni的bug
        self.userAccount = user
        
        //再把模型对象转换为字典
        let keys = ["access_token","expires_in","uid","name","avatar_large","expires_date"]
        
        let userInfo = user.dictionaryWithValuesForKeys(keys)
        
        //        print(userInfo)
        
        //保存字典
        let userDefaults = NSUserDefaults.standardUserDefaults()
        
        userDefaults.setObject(userInfo, forKey: userInfoKey)
        
        userDefaults.synchronize()
        
        print(NSHomeDirectory())
        
        
    }
    
    
    //读取数据
    func loadUserAccount() -> LBMUserAccount? {
        
        guard let dict = NSUserDefaults.standardUserDefaults().objectForKey(userInfoKey) as? [String : AnyObject] else {
            
            
            return nil
        }
        
        let user = LBMUserAccount(dict: dict)
        
        return user
        
    }
    
    
    
}